package com.example.studentvotesystem.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class FileUploadUtil {
    public static String saveFile(MultipartFile file, String uploadDir) throws IOException {
        // 确保上传目录存在
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        byte[] bytes = file.getBytes();
        Path path = Paths.get(uploadDir + newFilename);
        Files.write(path, bytes);

        return "/uploads/" + newFilename;
    }

    public static void deleteFile(String filePath, String uploadDir) throws IOException {
        if (filePath != null && filePath.startsWith("/uploads/")) {
            String filename = filePath.substring("/uploads/".length());
            Path path = Paths.get(uploadDir + filename);
            Files.deleteIfExists(path);
        }
    }
}
